package com.imooc.coupon.schedule;

import com.imooc.coupon.dao.CouponTemplateDao;
import com.imooc.coupon.entity.CouponTemplate;
import com.imooc.coupon.vo.TemplateRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用于定期清理过期优惠券的任务
 *
 * @Author Administrator
 * @Date 2021/10/25 20:13
 * @Version 1.0
 */
@Slf4j
@Component
public class ScheduledTask {

    private final CouponTemplateDao templateDao;

    @Autowired
    public ScheduledTask(CouponTemplateDao templateDao) {
        this.templateDao = templateDao;
    }

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void offlineCouponTemplate() {
        log.info("Start To Exppire  couponTemplate!");
        List<CouponTemplate> templates = templateDao.findAllByExpired(false);
        if (CollectionUtils.isEmpty(templates)) {
            log.info("Done To Expire  couponTemplate!");
            return;
        }
        Date cur = new Date();
        List<CouponTemplate> expireTemplates = new ArrayList<>(templates.size());
        templates.forEach(t -> {
            //根据优惠券模板中的过期时间
            TemplateRule rule = t.getRule();
            if (rule.getExpiration().getDeadLine() < cur.getTime()) {
                t.setExpired(true);
                expireTemplates.add(t);
            }
        });
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(expireTemplates)) {
            log.info(" Expire  couponTemplate num:{}", templateDao.saveAll(expireTemplates));
        }

    }
}
